package net.xuhf.service.impl;

import cn.hutool.core.date.DateUtil;
import net.xuhf.conf.MinioConfig;
import net.xuhf.dto.FileDTO;
import net.xuhf.service.IFileService;
import net.xuhf.utils.MinioUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class FileServiceImpl implements IFileService {

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private MinioConfig minioConfig;

    @Override
    public FileDTO upload(MultipartFile file) throws Exception {
        FileDTO fileDTO = new FileDTO();
        String bucketName = getBucketName();
        boolean bucketExists = minioUtil.bucketExists(bucketName);
        if (!bucketExists) {
            minioUtil.makeBucket(bucketName);
        }
        String fileName = minioUtil.putObject(minioConfig.getBucketName(), getPrefix(), file);
        fileDTO.setBucketName(minioConfig.getBucketName());
        fileDTO.setFileName(fileName);
        String url = minioUtil.getPresignedObjectUrl(bucketName, fileName, 1, TimeUnit.DAYS);
        fileDTO.setUrl(url);
        return fileDTO;
    }

    private String getBucketName() {
        return minioConfig.getBucketName();
    }

    private String getPrefix() {
        String day = DateUtil.format(new Date(), "yyyy/MM/dd");
        return day + "/";
    }
}
